library(data.table)
library(lubridate)
library(stringi)
library(stringr)
library(lfe)
library(sandwich)
library(lmtest)
library(margins)
library(ggplot2)
library(ggthemes)
library(scales)
library(stargazer)
# NB: stargazer should be installed with this fix: https://gist.github.com/alexeyknorre/b0780836f4cec04d41a863a683f91b53

# Declare working directory beforehand in an environment variable
# IMPERIAL_LEGAL_POLITICS_REPLICATION_PATH = "path_to_your_folder"
# with the aid of usethis::edit_r_environ()
# Restart R session for the changes to take effect
path <- Sys.getenv("IMPERIAL_LEGAL_POLITICS_REPLICATION_PATH")
setwd(path)

# Load objects with case-instance-side-outcome-level data
load("data/crimea_case_outcomes_side_instance.rdata")
load("data/krasnodar_case_outcomes_side_instance.rdata")

# Uniform outsider judge dummies
crimea_case_outcomes_side_instance[, any_judge_outsider := NA_real_]
crimea_case_outcomes_side_instance[ !is.na(any_judge_russian), any_judge_outsider := 0 ]
crimea_case_outcomes_side_instance[ any_judge_russian == 1, any_judge_outsider := 1 ]

krasnodar_case_outcomes_side_instance[, any_judge_outsider := NA_real_]
krasnodar_case_outcomes_side_instance[ !is.na(any_judge_krasnodar), any_judge_outsider := 0 ]
krasnodar_case_outcomes_side_instance[ any_judge_krasnodar == 0, any_judge_outsider := 1 ]

# Crimea dummy
crimea_case_outcomes_side_instance[, crimea := 1]
krasnodar_case_outcomes_side_instance[, crimea := 0]

# Combine the two cross-sections
kransodar_crimea_case_outcomes_side_instance <- rbind(crimea_case_outcomes_side_instance, krasnodar_case_outcomes_side_instance, fill = T)
# Keep only data after 2014
kransodar_crimea_case_outcomes_side_instance <- kransodar_crimea_case_outcomes_side_instance[ year(registrationDate) >= 2014 ]

##############################
# Prepare the data

# Create government win by instance object
government_win_instance <- kransodar_crimea_case_outcomes_side_instance[involved_government == 1 & was_appealed == 1 & government == 1, list(government_win = max(win, na.rm = T)), by = c("caseid", "instanceLevel") ]
# Remove cases with all missings in win rates
government_missing_cases <- unique(government_win_instance[ !is.finite(government_win)]$caseid)
government_win_instance <- government_win_instance[ !(caseid %in% government_missing_cases) ]

# Create federal agency win by instance object
federal_agency_win_instance <- kransodar_crimea_case_outcomes_side_instance[involved_federal_agency == 1 & was_appealed == 1 & federal_agency == 1, list(federal_agency_win = max(win, na.rm = T)), by = c("caseid", "instanceLevel") ]
# Remove cases with all missings in win rates
federal_agency_missing_cases <- unique(federal_agency_win_instance[ !is.finite(federal_agency_win)]$caseid)
federal_agency_win_instance <- federal_agency_win_instance[ !(caseid %in% federal_agency_missing_cases) ]

# Create regional/municipal agency win by instance object
regional_municipal_agency_win_instance <- kransodar_crimea_case_outcomes_side_instance[ involved_regional_municipal_agency == 1 & was_appealed == 1 & ( regional_agency == 1 | municipal_agency == 1), list(regional_municipal_agency_win = max(win, na.rm = T)), by = c("caseid", "instanceLevel") ]
# Remove cases with all missings in win rates
regional_municipal_agency_missing_cases <- unique(regional_municipal_agency_win_instance[ !is.finite(regional_municipal_agency_win)]$caseid)
regional_municipal_agency_win_instance <- regional_municipal_agency_win_instance[ !(caseid %in% regional_municipal_agency_missing_cases) ]

# Create local entity win (private disputes) by instance object
local_entity_win_instance <- kransodar_crimea_case_outcomes_side_instance[ involved_government == 0 & local_entities_only == 0 & was_appealed == 1 & local_entity == 1, list(local_entity_win = max(win, na.rm = T)), by = c("caseid", "instanceLevel") ]
# Remove cases with all missings in win rates
local_entity_missing_cases <- unique(local_entity_win_instance[ !is.finite(local_entity_win)]$caseid)
local_entity_win_instance <- local_entity_win_instance[ !(caseid %in% local_entity_missing_cases) ]

# Attach case characteristics of interest
case_chars <- c("caseid", "instanceLevel", "appeal", "any_judge_outsider", "year", "involved_federal_agency", "involved_regional_agency", "involved_municipal_agency", "involved_local_entity", "government_plaintiff", "federal_agency_plaintiff", "regional_agency_plaintiff", "municipal_agency_plaintiff", "local_entity_plaintiff", "caseTypeCode", "caseCategoryUnified", "caseCategoryRedux", "petty_case", "claimSum_deflated_wins_sinh", "presiding_judge", "lncountDocumentsByCourt", "lndays_elapsed", "local_entities_only", "dispute_type", "crimea")

government_win_instance <- merge(government_win_instance, unique(kransodar_crimea_case_outcomes_side_instance[, c(case_chars), with = F], by = c("caseid", "instanceLevel")), by = c("caseid", "instanceLevel"), all.x = T, all.y = F)
federal_agency_win_instance <- merge(federal_agency_win_instance, unique(kransodar_crimea_case_outcomes_side_instance[, c(case_chars), with = F], by = c("caseid", "instanceLevel")), by = c("caseid", "instanceLevel"), all.x = T, all.y = F)
regional_municipal_agency_win_instance <- merge(regional_municipal_agency_win_instance, unique(kransodar_crimea_case_outcomes_side_instance[, c(case_chars), with = F], by = c("caseid", "instanceLevel")), by = c("caseid", "instanceLevel"), all.x = T, all.y = F)
local_entity_win_instance <- merge(local_entity_win_instance, unique(kransodar_crimea_case_outcomes_side_instance[, c(case_chars), with = F], by = c("caseid", "instanceLevel")), by = c("caseid", "instanceLevel"), all.x = T, all.y = F)

##############################
# Fit TWFE regressions
# for government advantage
government_twfe_formula_basic_outsiderjudge <- as.formula("government_win ~ any_judge_outsider:crimea + any_judge_outsider + appeal + appeal:crimea | caseid | 0 | presiding_judge")
government_twfe_formula_interacted_outsiderjudge <- as.formula("government_win ~ any_judge_outsider:appeal:crimea + any_judge_outsider:crimea + any_judge_outsider:appeal + any_judge_outsider + appeal + appeal:crimea | caseid | 0 | presiding_judge")

## All non-petty cases
fit_government_twfe_outsiderjudge_basic_nonpetty <- felm(government_twfe_formula_basic_outsiderjudge, data = government_win_instance[ petty_case == 0 ])
fit_government_twfe_outsiderjudge_interacted_nonpetty <- felm(government_twfe_formula_interacted_outsiderjudge, data = government_win_instance[ petty_case == 0 ])

##############################
# Fit TWFE regressions
# for local entity advantage
local_entity_twfe_formula_basic_outsiderjudge <- as.formula("local_entity_win ~ any_judge_outsider:crimea + any_judge_outsider + appeal + appeal:crimea | caseid | 0 | presiding_judge")
local_entity_twfe_formula_interacted_outsiderjudge <- as.formula("local_entity_win ~ any_judge_outsider:appeal:crimea + any_judge_outsider:crimea + any_judge_outsider:appeal + any_judge_outsider + appeal + appeal:crimea | caseid | 0 | presiding_judge")

# All nonpetty cases
fit_local_entity_twfe_outsiderjudge_basic_nonpetty <- felm(local_entity_twfe_formula_basic_outsiderjudge, data = local_entity_win_instance[ petty_case == 0 ])
fit_local_entity_twfe_outsiderjudge_interacted_nonpetty <- felm(local_entity_twfe_formula_interacted_outsiderjudge, data = local_entity_win_instance[ petty_case == 0 ])

##############################
# Fit TWFE regressions
# for government advantage at different
# levels of government

###
# Federal agencies
federal_agency_twfe_formula_basic_outsiderjudge <- as.formula("federal_agency_win ~ any_judge_outsider:crimea + any_judge_outsider + appeal + appeal:crimea | caseid | 0 | presiding_judge")
federal_agency_twfe_formula_interacted_outsiderjudge <- as.formula("federal_agency_win ~ any_judge_outsider:appeal:crimea + any_judge_outsider:crimea + any_judge_outsider:appeal + any_judge_outsider + appeal + appeal:crimea | caseid | 0 | presiding_judge")

## All non-petty cases
fit_federal_agency_twfe_outsiderjudge_basic_nonpetty <- felm(federal_agency_twfe_formula_basic_outsiderjudge, data = federal_agency_win_instance[ petty_case == 0 ])
fit_federal_agency_twfe_outsiderjudge_interacted_nonpetty <- felm(federal_agency_twfe_formula_interacted_outsiderjudge, data = federal_agency_win_instance[ petty_case == 0 ])

###
# Regional/municipal agencies
regional_municipal_agency_twfe_formula_basic_outsiderjudge <- as.formula("regional_municipal_agency_win ~ any_judge_outsider:crimea + any_judge_outsider + appeal + appeal:crimea | caseid | 0 | presiding_judge")
regional_municipal_agency_twfe_formula_interacted_outsiderjudge <- as.formula("regional_municipal_agency_win ~ any_judge_outsider:appeal:crimea + any_judge_outsider:crimea + any_judge_outsider:appeal + any_judge_outsider + appeal + appeal:crimea | caseid | 0 | presiding_judge")

## All non-petty cases
fit_regional_municipal_agency_twfe_outsiderjudge_basic_nonpetty <- felm(regional_municipal_agency_twfe_formula_basic_outsiderjudge, data = regional_municipal_agency_win_instance[ petty_case == 0 ])
fit_regional_municipal_agency_twfe_outsiderjudge_interacted_nonpetty <- felm(regional_municipal_agency_twfe_formula_interacted_outsiderjudge, data = regional_municipal_agency_win_instance[ petty_case == 0 ])

##############################
# TABLE S10. Within-case advantage regression: Government vs. Private disputes, Federal agency vs. Private disputes, Regional/Municipal agency vs. Private disputes, and Private disputes where one of the parties is not local, Crimea and Krasnodar courts of first instance or appellate courts, 2014–2019, non-petty cases only

table_twfe_all <- stargazer(fit_government_twfe_outsiderjudge_basic_nonpetty, fit_government_twfe_outsiderjudge_interacted_nonpetty, fit_federal_agency_twfe_outsiderjudge_basic_nonpetty, fit_federal_agency_twfe_outsiderjudge_interacted_nonpetty, fit_regional_municipal_agency_twfe_outsiderjudge_basic_nonpetty, fit_regional_municipal_agency_twfe_outsiderjudge_interacted_nonpetty, fit_local_entity_twfe_outsiderjudge_basic_nonpetty, fit_local_entity_twfe_outsiderjudge_interacted_nonpetty, align = F, dep.var.labels = "", covariate.labels = c("Outsider judge", "Appeals", "Outsider judge $\\times$ Crimea", "Appeals $\\times$ Crimea", "Appeals $\\times$ Outsider judge", "Appeals $\\times$ Crimea", "Appeals $\\times$ Outsider judge $\\times$ Crimea"), column.labels = c("Government", "Federal agency", "Reg/mun agency", "Local entity"), column.separate = c(2), no.space = T, keep.stat = c("n", "rsq"), add.lines = list(c("Case type", rep("non-petty", 8)), c("Case FE", rep("yes", 8)), c("Judge FE", rep("no", 8))), notes = "TBA", type = "latex", style = "ajps")
cat(paste(table_twfe_all, collapse = "\n"), file = "tables/tableS10_twfe_all_krasnodar_crimea.tex")
